<template>
  <div class="__container_home_index">
    <a-row class="row" :gutter="[10, 10]">
      
      <a-col :span="8">
        <a-card class="card">
          <template #title>
            <label style="font-size: 25px">机票预定信息</label>
          </template>
          <a-table :data-source="bookingInfo.dataSource" :columns="bookingInfo.columns" :pagination="false">
            <template #bodyCell="{ record, index, column, text }">
              <template v-if="column.dataIndex === 'bookingStatus'">
                <template v-if="text === 'CONFIRMED'">
                  <Icon style="color: #52c41a; font-size: 20px; margin-bottom: -4px"
                    icon="material-symbols:check-box-sharp" />
                </template>
                <template v-else>
                  <Icon style="color: #be0b4a; font-size: 20px; margin-bottom: -4px"
                    icon="material-symbols:cancel-presentation-sharp" />
                </template>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card class="card chat">
          <template #title>
            <label style="font-size: 25px">Funnair support</label>
          </template>
          <div class="flex-grow">
            <a-card class="chat-body">
              <MessageList :list="messageInfo.list"></MessageList>
              <div id="chat-body-id" style="height: 5px; margin-top: 20px"></div>
            </a-card>
            <!-- <a-button type="primary" @click="changeFlag('1')">图形处理</a-button>
            <a-button type="primary" @click="changeFlag('2')">页面跳转</a-button>-->
            <a-button type="primary" @click="changeFlag('navigationAgent')">导航助手</a-button> 
            <a-button type="primary" @click="changeFlag('fileAnalyserAssistant')">文件分析助手</a-button>
            <a-button type="primary" @click="changeFlag('loadFileUrl')">加载文件</a-button>
            <a-button type="primary" @click="changeFlag('clearFileUrl')">清除文件</a-button>



          </div>
          <a-row class="footer" :gutter="10">
            <a-col :span="20">
              <a-input @keydown.enter="forHelp" v-model:value="question" :placeholder="msgPlaceholder"></a-input>
            </a-col>
            <a-col :span="4">
              <a-button @click="forHelp" :disabled="lock" type="primary">Send</a-button>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { PRIMARY_COLOR } from "@/base/constants";
import { nextTick, onMounted, reactive, ref } from "vue";
import { getHistoryMsg ,getFileAnalyserResult} from "@/api/service/booking";
import { Icon } from "@iconify/vue";
import Message from "@/views/home/Message.vue";
import MessageList from "@/views/home/MessageList.vue";
import type { FileEntity, MessageItem,chatEntity,contentsReq } from "@/types/message";
import { chat } from "@/api/service/assistant";
import { getUUID } from "ant-design-vue/lib/vc-dialog/util";
import { v4 as uuidv4 } from "uuid";
import { message } from "ant-design-vue";
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { timePickerProps } from "ant-design-vue/es/time-picker/time-picker";

const messageInfo: { cur: MessageItem | null; list: MessageItem[] } = reactive({
  cur: null,
  list: [
    {
      roleType: 'AI',
      contents:[{
        content:"HELLO啊",
        contentType:"text"
      }],
      time:"22002266225"
    }
  ],
});


const bookingInfo = reactive({
  dataSource: [],
  columns: [
    {
      title: "#",
      dataIndex: "bookingNumber",
      key: "bookingNumber",
    },
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "Date",
      dataIndex: "date",
      key: "date",
    },
    {
      title: "From",
      dataIndex: "from",
      key: "from",
    },
    {
      title: "To",
      dataIndex: "to",
      key: "to",
    },
    {
      title: "Status",
      dataIndex: "bookingStatus",
      key: "bookingStatus",
    },
    {
      title: "Booking Class",
      dataIndex: "bookingClass",
      key: "bookingClass",
    },
  ],
});
const question = ref("");
let scrollItem: any = null;

function scrollBottom() {
  scrollItem?.scrollIntoView({ behavior: "smooth", block: "end" });
}

const addMessage = (  roleType: "USER" | "AI",
                      content: String,
                      contentType: "text" | "file") =>{
  const cur = {
    roleType: roleType,
    contents: [
      {
        content: content,
        contentType: contentType
      }
    ],
    time: ""
  };
  messageInfo.cur = cur;
  messageInfo.list.push(cur);
  nextTick(() => {
    scrollBottom();
  });
}

const lock = ref(false);
let softFlag = ref<String>("2");
const msgPlaceholder = ref<String>("请输入内容")

/**
 * 添加聊天消息
 * @param content 
 */
function appendMessage(content: String) {

  if (content.startsWith('data:')) {
    const dataString = content.substring(5).trim();
    if (!dataString) {
      return;
    }

    try {
      const dataObject = JSON.parse(dataString);
      if (messageInfo.cur) {
        messageInfo.cur.contents[0].content += dataObject.contents[0].content;
      }
      // handleDataObject(dataObject);
    } catch (error) {
      console.error('Error parsing JSON:', error);
    }
  } else {
    if (!content  ) {
      return;
    }
    try {
      const dataObject = JSON.parse(content);
      if (messageInfo.cur) {
        messageInfo.cur.contents[0].content += dataObject.contents[0].content;
      }
      // handleDataObject(dataObject);
    } catch (error) {
      console.error('Error parsing JSON:', error);
    }
  }

  //  const  a = content.split(":")
  // if (messageInfo.cur) {
  //   messageInfo.cur.content =content;
  // }
  scrollBottom();
}


const msg = ref<chatEntity>({
  userId:'32',
  contents:[{
    content :"你好",
    contentType:"text",     
  }],
  businessFlag:'navigationAgent'  
});

function changeFlag(flag: String) {
  clearMsg()
    switch(flag){
      case 'navigationAgent':
      msg.value.businessFlag = flag

        msgPlaceholder.value = "导航助手"
        msg.value.contents[1] = {
          content: "",
          contentType: ""
        }
        break;
      case 'fileAnalyserAssistant':
      msg.value.businessFlag = flag

        msgPlaceholder.value = "文件分析助手";
        msg.value.contents[1] = {
          content: "http://srm-test-local.ci2c.com.cn/api/admin/sys-file/uploaded/ci2c/g2s/2024/12/30/61a7477d6df549a4af4ded8672c30f6e.docx",
          contentType: "file"
        }
        break;
      case 'clearFileUrl':
        msg.value.contents[1] = {
          content: "",
          contentType: ""
        }
        break;
    }
}

const clearMsg = () => {
  msg.value = {
    userId: '',
    contents: [],
    businessFlag: ''
  };
};

const fileAnalyser = () => {
    const fileEntityList = [{
      fileName: "这是文件名",
      fileUrl: "https://static.ci2c.com.cn/g2s/2024/12/20/12dee111319048a18ec6c910a89497d6.docx"
    }]
    getFileAnalyserResult(fileEntityList).then(()=>{
      
    })
}

async function forHelp() {
  if (lock.value) {
    message.warn("助手正在生成, 请耐心等候");
    return;
  }

  msg.value.contents[0] = {
      content: question.value.trim(),
      contentType: "text"
  }
  msg.value.userId = '32'
  if (!question.value.trim()) return; // 如果用户输入为空，则不发送请求

  addMessage("USER", question.value.trim(),"text");
  question.value = "";

  lock.value = true; // 在发送请求前锁定，防止重复请求
  console.log('实际请求',msg.value);
  
  try {
    
    const response = await fetch('/api/chat/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(msg.value),
    });


    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const dataStream = response.body;
    if (!dataStream) {
      throw new Error('No stream available from the server');
    }

    const reader = dataStream.getReader();

    const decoder = new TextDecoder('utf-8');

    addMessage("AI", "","text"); // 开始接收助手回复


    while (true) {
      const { done, value } = await reader.read();
      // console.log("----------------",done);
      // console.log("----------------",done);
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      appendMessage(chunk);
    }

  } catch (error) {
    console.error('Error:', error);
    // 可以在这里添加错误处理逻辑，例如通知用户或重试机制
  } finally {
    lock.value = false; // 确保最终解锁，允许再次发送请求
  }
}
const loadMsg = ()=> {
  getHistoryMsg({ userId: 32 }).then((res) => {
    // const res2 = res.data.map((item: MessageItem) => {
    //   console.log("这是什么书数据",item);
    //   const temp = item;
      
    //   // item.roleType == 'USER' ? temp['roleType'] = 'user' : temp['role'] = 'assistant'
    //   return temp;
    // })
    console.log("这是什么书数据",res.data);
    
    messageInfo.list = res.data;
  });
}

let __null = PRIMARY_COLOR;
onMounted(() => {
  scrollItem = document.getElementById("chat-body-id");
  loadMsg();
});
</script>
<style lang="less" scoped>
.__container_home_index {
  height: 100vh;
  max-height: 100vh;
  overflow: auto;
  padding-top: 2px;

  .row {
    height: 100%;
  }

  .card {
    height: 100%;
  }

  :deep(.ant-card-body) {
    height: calc(100vh - 180px);
    display: flex;
    flex-direction: column;
    padding: 5px;
    border-radius: 0;

    .chat-body {
      border: none;
      height: calc(100% - 80px);
      overflow: auto;
      background: #f4f5f7;
    }
  }

  .flex-grow {
    flex-grow: 1;
    /* 让其他元素占据剩余空间 */
  }

  .footer {
    width: 100%;
  }
}
</style>
